package zack.gateway.core.socket.handlers;

import zack.gateway.core.mapping.HttpStatement;
import zack.gateway.core.session.Configuration;
import zack.gateway.core.socket.BaseHandler;
import zack.gateway.core.socket.agreement.AgreementConstants;
import zack.gateway.core.socket.agreement.GatewayResultMessage;
import zack.gateway.core.socket.agreement.ResponseParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;

/**鉴权处理器
 * @author A1793
 */
public class AuthorizationHandler extends BaseHandler<FullHttpRequest> {

    private final Logger logger = LoggerFactory.getLogger(AuthorizationHandler.class);

    private final Configuration configuration;

    public AuthorizationHandler(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest request) throws ExecutionException, InterruptedException {

       try{
           HttpStatement httpStatement = channel.attr(AgreementConstants.HTTP_STATEMENT).get();
           //判断该uri是否需要鉴权
           if( httpStatement.isAuth()){
               String uid = request.headers().get("uid");
               String token = request.headers().get("token");
               //鉴权
               if (null == token || "".equals(token)) {
                   DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._400.getCode(), "对不起，你的 token 不合法！"));
                   channel.writeAndFlush(response);
               }
               boolean status = configuration.authValidate(uid, token);
               if(status){
                   request.retain();
                   ctx.fireChannelRead(request);
               }else {
                   DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._403.getCode(), "对不起，你无权访问此接口！"));
                   channel.writeAndFlush(response);
               }
        }else{
               //不需要鉴权的放行
               request.retain();
               ctx.fireChannelRead(request);
           }
    }catch(Exception e){
           // 4. 封装返回结果
           DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败！" + e.getMessage()));
           channel.writeAndFlush(response);
       }

    }
}
